/**
 * 
 */
package com.htht.tourism.action;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.htht.tourism.domain.Response;
import com.htht.tourism.domain.Sources;
import com.htht.tourism.domain.link.ScenicParam;
import com.htht.tourism.domain.link.SourcesParam;
import com.htht.tourism.intf.SourcesService;
import com.htht.tourism.utils.ConfigUtil;
import com.htht.tourism.utils.ValidatorResultHandler;

/**
 * SpringMVC中的文件上传 
 * @see 第一步：由于SpringMVC使用的是commons-fileupload实现，故将其组件引入项目中 
 * @see       这里用到的是commons-fileupload-1.2.2.jar和commons-io-2.0.1.jar 
 * @see 第二步：在####-servlet.xml中配置MultipartResolver处理器。可在此加入对上传文件的属性限制 
 * @see 第三步：在Controller的方法中添加MultipartFile参数。该参数用于接收表单中file组件的内容 
 * @see 第四步：编写前台表单。注意enctype="multipart/form-data"以及<input type="file" name="****"/> 
 * @author wuqiwei
 *
 */
@Controller
@ResponseBody
@RequestMapping("/sources")
public class SourcesController {
	@Resource
	private SourcesService sourcesService;
	
	/**
	 * 上传图片
	 * @author:wuqiwei
	 * @param @param file
	 * @param @param request
	 * @param @return
	 * @date:2017年3月20日下午3:39:51
	 */
	@RequestMapping(value = "/ImgUpload", method = RequestMethod.POST)
	public Map enterpriseUploadHeading(
			@RequestParam(value = "file",required = false) MultipartFile[] file,HttpServletRequest request){
		Map map = new HashMap();
		String path = request.getSession().getServletContext().getRealPath(ConfigUtil.getProperty("default","sources"));
	
		String status = request.getParameter("status");
		String sourceid = request.getParameter("source_id");
		String id_type = request.getParameter("id_type");//行业类型(如：type=5  id对于与房源表中具体房源id)
		String intro = request.getParameter("intro");//图片描述
		String url_type = request.getParameter("url_type");//url类型(  0：图片,1：音频,2：视频)
		String sourcesid = request.getParameter("sourcesid");//资源id
		//如果只是上传一个文件，则只需要MultipartFile类型接收文件即可，而且无需显式指定@RequestParam注解  
        //如果想上传多个文件，那么这里就要用MultipartFile[]类型来接收文件，并且还要指定@RequestParam注解  
        //并且上传多个文件时，前台表单中的所有<input type="file"/>的name都应该是myfiles，否则参数里的myfiles无法获取到所有上传的文件  
		SourcesParam param = new SourcesParam();
		int i = 0;
		if(file.length == 0){//如果小于0 证明是删除图片
			 if(sourcesid != null && !sourcesid.equalsIgnoreCase("")){//当不为空的时候 执行删除图片操作
         		String[] sourcesids = sourcesid.split(",");
	        		param.setSourcesids(Long.valueOf(sourcesids[i]));
	        		int c =  sourcesService.delSources(param);
         	}
		}
		if(status.equalsIgnoreCase("1")){//当status为1时 走下面的修改接口
        	if(sourcesid != null && !sourcesid.equalsIgnoreCase("")){//当不为空的时候 执行删除操作
        		String[] sourcesids = sourcesid.split(",");
        		for(int j = 0;j<sourcesids.length;j++){
        			param.setSourcesids(Long.valueOf(sourcesids[j]));
        			int c =  sourcesService.delSources(param);
        		}
        	}
        	map.put("success", true);
		}
		for(MultipartFile myfile : file){
			 if(myfile.isEmpty()){
				 	map.put("msg", "文件未上传");
	            }else{  
	            	Date date = new Date();
	        		String time =  String.valueOf(date.getTime());
	            	String filename = myfile.getOriginalFilename();//文件的名字
	        		param.setName(time+filename);
	        		param.setId_type(Long.valueOf(id_type));
	        		param.setUrl("MountainTourism"+ConfigUtil.getProperty("default","sources")+time+filename);
	        		param.setIntro(intro);
	        		param.setSource_id(Long.valueOf(sourceid));
	        		File target = new File(path,time+filename);
	        		if(!target.exists()){
	        			target.mkdirs();
	        		}
	        		try {
	        			myfile.transferTo(target);
	        			List<Sources> list = sourcesService.getAll(param);//查询是否含有这条记录
	        			String souceid = "";
	        			if(list.size() > 0 && status.equalsIgnoreCase("1")){//判断当大于0时 修改这条记录
	        				int b = sourcesService.update(param);//修改信息
	        				if(!myfile.isEmpty()){//判断当资源id 为null时 执行添加操作
	        					int p = sourcesService.add(param);//添加信息
	        				}
	        				i++;
	        			}else{
	        				int a = sourcesService.add(param);//添加信息
	        				souceid = String.valueOf(param.getId());
	        				i++;
	        			}
	        			map.put(souceid, "MountainTourism"+ConfigUtil.getProperty("default","sources")+time+filename);
	        			map.put("success", true);
	        			//	        			return Response.getInstance().success("MountainTourism"+ConfigUtil.getProperty("default","sources")+time+filename);
	        		} catch (IllegalStateException e) {
	        			map.put("msg", e.getMessage());
//	        			return Response.getInstance().failure(e.getMessage());
	        		} catch (IOException e) {
	        			map.put("msg", e.getMessage());
//	        			return Response.getInstance().failure(e.getMessage());
	        		}
	            }  
		}
		return map;
	}
	
	/**
	 * 删除图片
	 * @author:wuqiwei
	 * @param @param param
	 * @param @param result
	 * @param @return
	 * @date:2017年5月2日下午4:54:10
	 */
	@RequestMapping(value = "/del", method = RequestMethod.POST)
	public Response del(@RequestBody @Validated ScenicParam param,
			BindingResult result) {
		Response retVal = ValidatorResultHandler.handle(result);
		if (retVal == null) {
			int a = this.sourcesService.del(param);
			if (a > 0) {
				return Response.getInstance().success(a);
			} else {
				return Response.getInstance().failure("删除失败！");
			}
		} else {
			return retVal;
		}
	}
}
